--[[----------------------------------------------------------------------------
	Copyright 2008 João Liborio Cardoso
	All rights reserved
	
	Scrap is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3 as published by the Free Software Foundation.
	Scrap is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License (<http://www.gnu.org/licenses/>) for more details.
---------------------------------------------------------------------------]]--

Scrap = CreateFrame('Button', 'Scrap', MerchantBuyBackItem, 'ItemButtonTemplate')

local moneyTypes = {'Gold', 'Silver', 'Copper'}
local L, value


--[[ Startup ]]--

function Scrap:Load()
	local Icon = self:CreateTexture(self:GetName()..'CoinTexture', 'ARTWORK')
	Icon:SetTexture('Interface/Icons/INV_Misc_Coin_02')
	Icon:SetTexCoord(0.07, 0.93, 0.07, 0.95)
	Icon:SetHeight(29.5) Icon:SetWidth(29)
	Icon:ClearAllPoints()
	Icon:SetPoint('CENTER', -0.3, -0.5)
	
	local Border = _G[self:GetName()..'IconTexture']
	Border:SetTexture('Interface/MerchantFrame/UI-Merchant-RepairIcons')
	Border:SetHeight(63.5) Border:SetWidth(36.5)
	Border:SetTexCoord(0, 0.28125, 0, 1)
	Border:ClearAllPoints()
	Border:SetPoint('TOPRIGHT', -0.7, -0.5)
	
	self.Tooltip = CreateFrame('GameTooltip', 'ScrapTooltip', nil, 'GameTooltipTemplate')
	self:SetNormalTexture(nil)
	
	self:RegisterForClicks('LeftButtonUp', 'RightButtonUp')
	self:SetScript('OnReceiveDrag', self.OnReceiveDrag)
	self:SetScript('OnEnter', self.OnEnter)
	self:SetScript('OnLeave', self.OnLeave)
	self:SetScript('OnClick', self.OnClick)
	
	self:SetScript('OnEvent', function() self[event](self) end)
	self:RegisterEvent('VARIABLES_LOADED')
	self:RegisterEvent('MERCHANT_CLOSED')
	self:RegisterEvent('MERCHANT_SHOW')
	
	self:Hook('MerchantFrame_UpdateRepairButtons', 'UpdateButtonPosition')
	self:Hook('SetTooltipMoney', 'UpdateJunkValue')
end

function Scrap:Hook(...)
	local t = {...}
	local arg = tremove(t)
	tinsert(t, function(...) self[arg](self, ...) end)
	hooksecurefunc(unpack(t))
end

function Scrap:OptionsEnabled() 
	return select(4, GetAddOnInfo('Scrap_Options'))
end

function Scrap:VARIABLES_LOADED()
	L = self.Locals
	Scrap_SV = Scrap_SV or {profiles = {}, profileKeys = {}}
	self:SetProfile(self:GetCurrentProfile() or self:GetPlayerName())
end


--[[ Profiles ]]--

function Scrap:SetProfile(name)
	Scrap_SV.profileKeys[self:GetPlayerName()] = name
	Scrap_SV.profiles[name] = Scrap_SV.profiles[name] or {help = true, links = {}}
	self.sets = Scrap_SV.profiles[name]
end

function Scrap:GetCurrentProfile()
	return Scrap_SV.profileKeys[self:GetPlayerName()]
end

function Scrap:GetPlayerName()
	return format('%s - %s', UnitName('player'), GetRealmName())
end


--[[ Button Scripts ]]--

function Scrap:OnEnter()
	GameTooltip:SetOwner(self, 'ANCHOR_RIGHT')
	
	local infoType ,_, itemID = GetCursorInfo()
	if infoType == 'item' then
		if self:IsJunk(itemID) then
			GameTooltip:SetText(L.Remove, 1, 1, 1)
		else
			GameTooltip:SetText(L.Add, 1, 1, 1)
		end
	elseif self.sets.help then
		GameTooltip:SetText('Scrap', 1, 1, 1)
		GameTooltip:AddLine(L.SellJunkTip, 1, 0.82, 0)
		
		if self:OptionsEnabled() then
			GameTooltip:AddLine(L.ShowMenuTip, 1, 0.82, 0)
		end
		
		GameTooltip:AddLine(L.DragItemTip, 1, 0.82, 0)
	else
		local money = self:GetJunkValue()
		if money > 0 then
			GameTooltip:SetText(L.SellJunk, 1, 0.82, 0)
			SetTooltipMoney(GameTooltip, money)
		end
	end
	
	GameTooltip:Show()
end

function Scrap:OnLeave()
	GameTooltip:Hide()
end

function Scrap:OnClick(arg1)
	if arg1 == 'LeftButton' then
		self:SellJunk()
		self:GetScript('OnLeave')()
	elseif self:OptionsEnabled() then
		if not IsAddOnLoaded('Scrap_Options') then
			LoadAddOn('Scrap_Options')
		end
		ToggleDropDownMenu(1, nil, self.Dropdown, self, 0, 0)
	end
end

function Scrap:OnReceiveDrag()
	local infoType ,_, itemID = GetCursorInfo()
	if infoType == 'item' then
		local itemName = GetItemInfo(itemID)
		self.sets.links[itemName] = not self.sets.links[itemName] or nil
		
		if self:IsJunk(itemID) then
			self:SystemMessage(L.Added, itemID)
		else
			self:SystemMessage(L.Removed, itemID)
		end
		self:UpdateButtonState()
	end
	ClearCursor()
end


--[[ Events ]]--

function Scrap:MERCHANT_SHOW()
	if self.sets.autoSell then
		self:SellJunk()
	end
	self:RegisterEvent('BAG_UPDATE')
	self:UpdateButtonState()
end

function Scrap:MERCHANT_CLOSED()
	self:UnregisterEvent('BAG_UPDATE')
end

function Scrap:BAG_UPDATE()
	self:UpdateButtonState()
end


--[[ Button Functions ]]--

function Scrap:UpdateButtonState()
	local disabled = self:GetJunkValue() == 0
	_G[self:GetName()..'CoinTexture']:SetDesaturated(disabled)
    _G[self:GetName()..'IconTexture']:SetDesaturated(disabled)
end

function Scrap:UpdateButtonPosition()
	if CanMerchantRepair() then
		local off, scale
		if CanGuildBankRepair() then
			off, scale = -3.5, 0.9
			MerchantRepairAllButton:SetPoint('BOTTOMRIGHT', MerchantFrame, 'BOTTOMLEFT', 132.5, 89)
		else
			off, scale = -1.5, 1
		end
		self:SetPoint('RIGHT', MerchantRepairItemButton, 'LEFT', off, 0)
		self:SetScale(scale)
	else
		self:SetPoint('RIGHT', MerchantBuyBackItem, 'LEFT', -17, 0.5)
		self:SetScale(1.1)
	end
end


--[[ Junk Functions ]]--

function Scrap:SellJunk()
	self:ForAllJunk(function(bag, slot)
		UseContainerItem(bag, slot)
	end)
	local value = self:GetJunkValue()
	if value and value > 0 then
		self:SystemMessage(L.JunkSold, self:FormatMoney(value))
	end
end

function Scrap:IsJunk(itemID)
	if itemID and type(itemID) == 'string' then
		local itemName, _, quality = GetItemInfo(itemID)
		return quality == 0 and not self.sets.links[itemName] or quality ~= 0 and self.sets.links[itemName]
	end
end

function Scrap:ForAllJunk(func)
	for bag = 0,NUM_BAG_FRAMES do
    	for slot = 0, GetContainerNumSlots(bag) do
      		if self:IsJunk(GetContainerItemLink(bag, slot)) then
      			func(bag, slot, itemID)
      		end
	    end
	end
end

function Scrap:GetJunkValue()
	value =  0
	self:ForAllJunk(function(bag, slot)
		self.Tooltip:SetBagItem(bag, slot)
	end)
    return value
end

function Scrap:UpdateJunkValue(frame, money)
	if frame == self.Tooltip and MerchantFrame:IsShown() then
		value = value + money
	end
end


--[[ Print Fuctions ]]--

function Scrap:Print(mainString,...)
	self:AddMessage(nil, '|cff33ff99Scrap|r: '..tostring(mainString),...)
end

function Scrap:SystemMessage(...)
	self:AddMessage(ChatTypeInfo.LOOT, ...)
end

function Scrap:FormatMoney(value)
	local string = ''
	for i,name in pairs(moneyTypes) do
		local newVal = floor(value / (10 ^ (2 * (3 - i))) % 100)
		if newVal > 0 then
			string = string .. newVal .. self:GetCoinTexture(name)
		end
	end
	return string
end

function Scrap:AddMessage(color, ...)
	color = color or {}
	DEFAULT_CHAT_FRAME:AddMessage(format(self:TostringArgs(...)), color.r, color.g, color.b)
end

function Scrap:TostringArgs(arg1, ...)
	if arg1 then
		return tostring(arg1), self:TostringArgs(...)
	end
end

function Scrap:GetCoinTexture(name)
	return format('|TInterface\\Addons\\Scrap\\Textures\\%s:19:19:2:1|t  ', name)
end


--[[ Call Addon ]]--

Scrap:Load()
MerchantRepairText:SetAlpha(0)